package br.com.rapidrest.demo.ioc;

import java.lang.reflect.Field;

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import br.com.rapidrest.chain.BasicChainContext;
import br.com.rapidrest.exception.InjectionException;
import br.com.rapidrest.ioc.FieldHandler;

/**
 * EJB field handler is responsible of injecting EJB fields at page beans. It is
 * implemented for illustration purposes only.
 * 
 * @author Filipe Carmona Simoes
 * 
 */
public class EJBFieldHandler implements FieldHandler {

	@Override
	public void handle(Field field, Object target, BasicChainContext context)
			throws InjectionException {
		if (field.isAnnotationPresent(EJB.class)) {
			try {
				Class<?> type = field.getType();
				InitialContext ctx = new InitialContext();
				Object service = ctx
						.lookup(type.getSimpleName() + "Bean/local");
				field.setAccessible(true);
				field.set(target, service);
			} catch (NamingException e) {
				throw new InjectionException(e);
			} catch (IllegalArgumentException e) {
				throw new InjectionException(e);
			} catch (IllegalAccessException e) {
				throw new InjectionException(e);
			}
		}
	}

	@Override
	public void end(Field field, Object target, BasicChainContext context)
			throws InjectionException {
		if (field.isAnnotationPresent(EJB.class)) {
			try {
				field.setAccessible(true);
				field.set(target, null);
			} catch (IllegalArgumentException e) {
				throw new InjectionException(e);
			} catch (IllegalAccessException e) {
				throw new InjectionException(e);
			}
		}
	}

}